package src

import (
	"fmt"
	"github.com/gocolly/colly"
	"github.com/gocolly/colly/extensions"
	"github.com/tidwall/gjson"
	"log"
	"strings"
)

type Args struct {
	CookieV      string
	Where        []string
	Exclude50WUP bool // 剔除开户要求大于50万的股票
}

func IwencaiSpider(args Args) [][]map[string]string {
	// 实例化
	url := fmt.Sprintf("http://www.iwencai.com/stockpick/load-data?"+
		"w=%s&"+
		"typed=1&"+
		"ts=1&f=1&"+
		"qs=result_rewrite&"+
		"querytype=stock&"+
		"tid=stockpick", strings.Join(args.Where, "；"))

	spider := colly.NewCollector()
	spider.Async = true
	extensions.RandomUserAgent(spider) // 设置随机UserAgent，以达到真实模拟浏览器
	extensions.Referer(spider)
	spider.Limit(&colly.LimitRule{
		Parallelism: 1,
	})
	var content [][]map[string]string
	//var body interface{}
	spider.OnResponse(func(response *colly.Response) {
		log.Println("获得响应", response.StatusCode, response.Request.URL)


		title := gjson.Get(string(response.Body), "data.result.title").Array()
		result := gjson.Get(string(response.Body), "data.result.result").Array()
		if len(result) == 0 {
			panic("该条件下，没有查到数据")
		}
		//fmt.Println("value",title)
		//fmt.Println("value",result)
		var msg []map[string]string
		for _, r := range result {
			var mid = make(map[string]string)
			for index := 0; index < len(title); index++ {
				k_ := strings.ReplaceAll(title[index].String(), "<br>", "")

				mid[k_] = r.Array()[index].String()
			}
			msg = append(msg, mid)
		}
		var stockCode []string
		for _, m := range msg {
			//fmt.Println(m)
			var oneStock []map[string]string
			block := ""
			code := m["股票代码"][0:3]
			switch code {
			case "600", "601", "603", "605":
				block = "上交"
			case "688":
				if args.Exclude50WUP {
					continue
				}
				block = "上交科创板"
			case "000", "001", "002", "003":
				block = "深交所"
			case "300", "301":
				if args.Exclude50WUP {
					continue
				}
				block = "深交所创业板"
			default:
				block = "未知板块"
			}
			stockCode = append(stockCode, m["股票代码"])
			m["交易板块"] = block
			for k, v := range m {
				oneStock = append(oneStock, map[string]string{
					"tag":  "text",
					"text": fmt.Sprintf("%-60s =========> %20s\n", k, v),
					//"text": fmt.Sprintf("%s\n",FmtString(k,v,"======>",50)),
				})
			}
			oneStock = append(oneStock, map[string]string{
				"tag":  "text",
				"text": fmt.Sprintf("%s %s", "\n", "\n"),
			})
			content = append(content, oneStock)

		}
		//fmt.Println(content)
		var summary []map[string]string
		summary = append(summary, map[string]string{
			"tag":"text",
			"text": fmt.Sprintf("总计推出股票%d只: \n%v", len(content), stockCode),
		})
		content = append(content, summary)

	})
	spider.OnError(func(response *colly.Response, err error) {
		log.Println("错误响应",
			response.StatusCode,
			response.Request.URL,
			response.Request.Headers,
			response.Headers,
			err,
		)
		if response.StatusCode != 200 {
			panic(fmt.Sprintf("接口异常 %d:\n%s", response.StatusCode, string(response.Body)))
		}
	})

	spider.OnRequest(func(request *colly.Request) {
		request.Headers.Set("hexin-v", args.CookieV)
		request.Headers.Set("Accept", "application/json, text/javascript, */*; q=0.01")
		log.Println("请求路径:", request.URL)
		log.Println("请求头:", request.Headers)
	})

	spider.Request("Get", url, nil, nil, nil)
	spider.Wait()
	return content

}
